import { Router } from 'express';
import Paths from '@src/common/constants/Paths';
import { prisma } from '@src/common/database';
import { jsonResponse } from '@src/common/util/bigint-serializer';
import { sendToLiveRoom } from './common/live-sse';

const router = Router();
const SESSION_COOKIE = 'sid';

async function getCurrentUser(req: any) {
  try {
    const sid = req.cookies?.[SESSION_COOKIE];
    if (!sid) return null;
    const sess = await prisma.userSession.findUnique({ where: { id: BigInt(sid) } });
    if (!sess || new Date(sess.expiredAt) < new Date()) return null;
    const user = await prisma.user.findUnique({ where: { id: sess.userId } });
    return user;
  } catch {
    return null;
  }
}

// POST /api/live/rooms/:roomId/gifts/send
router.post(Paths.Live.Rooms + '/:roomId/gifts/send', async (req, res) => {
  try {
    const user = await getCurrentUser(req);
    if (!user) return res.status(401).json({ error: '로그인되지 않음' });

    const { roomId } = req.params as any;
    const { giftId, quantity = 1 } = req.body ?? {};

    // 디버그 로그 추가
    console.log('선물 전송 요청 수신:', {
      userId: String(user.id),
      roomId,
      giftId,
      quantity,
      giftIdType: typeof giftId,
      requestBody: req.body
    });

    if (!giftId) return res.status(400).json({ error: 'giftId 필수' });
    const qty = Math.max(1, Number(quantity || 1));

    const result = await prisma.$transaction(async (tx) => {
      const gift = await tx.gift.findUnique({ where: { id: BigInt(giftId) } });
      console.log('선물 검색 결과:', { giftId, gift: gift ? { id: String(gift.id), name: gift.name, isActive: gift.isActive } : null });
      if (!gift || !gift.isActive) throw new Error('선물이 존재하지 않거나 비활성화됨');

      // 라이브룸 정보 조회하여 channelId 가져오기
      const liveRoom = await tx.liveRoom.findUnique({ where: { id: BigInt(roomId) } });
      console.log('라이브룸 검색 결과:', { roomId, liveRoom: liveRoom ? { id: String(liveRoom.id), status: liveRoom.status } : null });
      if (!liveRoom) throw new Error('라이브룸이 존재하지 않음');

      const total = BigInt(gift.pricePoints) * BigInt(qty);

      // 관리자는 포인트 차감 없이 선물 발송, 일반 사용자는 포인트 확인
      if (user.role !== 'admin') {
        let wallet = await tx.userWallet.findUnique({ where: { userId: user.id } });
        console.log('사용자 지갑 정보:', { userId: String(user.id), wallet: wallet ? { balance: String(wallet.pointsBalance) } : null, total: String(total) });
        if (!wallet || wallet.pointsBalance < total) throw new Error('포인트 부족');

        const after = wallet.pointsBalance - total;
        await tx.userWallet.update({ where: { userId: user.id }, data: { pointsBalance: after } });
      }

      const send = await tx.giftSend.create({
        data: {
          liveRoomId: BigInt(roomId),
          channelId: liveRoom.channelId,
          giftId: gift.id,
          quantity: qty,
          unitPricePoints: gift.pricePoints,
          totalPoints: total,
          senderUserId: user.id,
        },
      });

      // 관리자가 아닌 경우에만 포인트 차감 기록
      if (user.role !== 'admin') {
        await tx.pointLedger.create({
          data: {
            userId: user.id,
            deltaPoints: -total,
            reason: 'gift_send',
            relatedType: 'gift_send',
            relatedId: send.id,
          },
        });
      }

      return { send, gift };
    });

    // SSE로 선물 메시지 방송
    try {
      const payload = {
        id: String(result.send.id),
        content: `${result.gift.name} x${result.send.quantity}을(를) 보냈습니다`,
        username: (user as any)?.nickname || (user as any)?.name || '나',
        avatar: (user as any)?.avatarUrl || 'https://picsum.photos/32',
        timestamp: new Date(),
        isGift: true,
        giftId: String(result.gift.id),
        giftEffectPreset: result.gift.effectPreset || 'burst',
        quantity: Number(result.send.quantity || 1),
      };
      sendToLiveRoom(String((req.params as any).roomId), 'gift', payload);
    } catch {}

    return jsonResponse(res, result);
  } catch (err: any) {
    console.error('선물 전송 실패:', err);
    return res.status(400).json({ error: err.message || '선물 전송 실패' });
  }
});

export default router;

